import os
import sys
import time
import json
import django
import uuid
import datetime

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
print(os.path.abspath(__file__))
print(BASE_DIR)
sys.path.extend([BASE_DIR, ])
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "finance_c2c.settings")
django.setup()

from apps.coffee.models import CoffeeOrder, GiveRecord
from core.wchat.models import RefundRecord
from django.db.models import Q
from finance_c2c.local_settings import Config
from core.yl.client import YLClient
from core.yl.models import YLRefundRecord
from core.wchat.wx_base import WxBase
from finance_c2c.local_settings import ONLINE
from apps.supply_order.models import RefundRecord as BaseRefundRecord
from django.contrib.auth import get_user_model
from apps.coffee.config import system_user
from core.tl.models import AllinPayUnifiedOrder

User = get_user_model()

wx_base = WxBase()

yl_client = YLClient()


def make_fail_refund():
    start_time = datetime.datetime.now() - datetime.timedelta(minutes=120)
    # 查询最近一个小时，制作是失败的，并且支付时间是超过5分钟的,支付成功的退钱退券，支付失败的退券
    end_pay_time = datetime.datetime.now() - datetime.timedelta(minutes=60)
    # 小于五分钟前 大于开始时间（自定义的）
    base_orders = CoffeeOrder.objects.filter(Q(create_time__lte=end_pay_time), Q(create_time__gte=start_time))
    # base_orders = CoffeeOrder.objects.filter(Q(pay_time__lte=end_pay_time))
    orders = base_orders.filter(~Q(coffee_make_result=1), Q(result=0) | Q(result=4) | Q(result=1))
    system_user_instance = User.objects.get(mobile=system_user)
    for i in orders:
        if i.result == 1:  # 支付是成功的
            if i.pay_type == 98:  # 微信小程序退款 支付成功退钱
                total_fee = i.total_fee
                refund_fee = i.total_fee
                out_refund_no = uuid.uuid1().hex
                out_trade_no = i.out_trade_no
                refund_notify_url = Config.host + "/coffee/api/refundCoffee"
                status, message = RefundRecord.objects.wx_refund_v2(total_fee, refund_fee, out_refund_no, out_trade_no,
                                                                    notify_url=refund_notify_url, pay_type="mini")
                if status:
                    pass
                else:
                    status, message = RefundRecord.objects.wx_refund(total_fee, refund_fee, out_refund_no, out_trade_no,
                                                                     notify_url=refund_notify_url, pay_type="mini")
            elif i.pay_type == 1:  # 微信退款
                total_fee = i.total_fee
                refund_fee = i.total_fee

                out_refund_no = uuid.uuid1().hex
                out_trade_no = i.out_trade_no
                refund_notify_url = Config.host + "/coffee/api/refundCoffee"
                status, message = RefundRecord.objects.wx_refund_v2(total_fee, refund_fee, out_refund_no, out_trade_no,
                                                                    notify_url=refund_notify_url, pay_type="js")
                if status:
                    pass
                else:
                    status, message = RefundRecord.objects.wx_refund(total_fee, refund_fee, out_refund_no,
                                                                     out_trade_no,
                                                                     notify_url=refund_notify_url, pay_type="js")
            elif i.pay_type == 4:  # 银联支付
                out_trade_no = i.out_trade_no
                refundOrderId = yl_client.new_unique_value
                status, message = YLRefundRecord.objects.yl_refund(None, out_trade_no, refundOrderId=refundOrderId)
                if status:
                    data = {"refund_fee": i.payment, "refund_type": 4, "out_refund_no": refundOrderId}
                    refund_instance = BaseRefundRecord.objects.create_refund(**data)
                    # 退券
                    i.refund_coupon(result=2, refund=refund_instance)
                else:
                    content = "支付订单号:%s\n\n退款订单号%s\n\n%s" % ("out_trade_no", "refundOrderId", message)
                    if ONLINE:
                        user_id = "ojh4ptynBWEzmimzXxZFGtiOJAsY"
                        wx_base.client.message.send_text(user_id, content)
                    else:
                        print(content)
            elif i.pay_type == 97: # 云微退款
                mchOrderNo = i.orderNo
                amount = i.total_fee
                # 只申请退款
                AllinPayUnifiedOrder.objects.create_refund_order(mchOrderNo, amount)


            elif i.pay_type == 99:  # 免费券
                i.refund_coupon(result=2)
            else:
                pass
            # 只要支付成功 并且给了券的 就退券
            if hasattr(i, "giverecord"):
                i.giverecord.update_status_3(refund_user=system_user_instance)
        else:
            i.refund_coupon(result=3)  # 未支付成功的，取消订单


if __name__ == '__main__':
    make_fail_refund()
